<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;
use Traits\DataTree;

/**
 * 组织表
 */
class OrganizationController extends AdminController
{
    use DataTree;

	protected string $table = "organizations";

    protected string $model = "organization";

	#[NoReturn] public function init(): void
    {
        parent::init();
        if (Request::input("title")) {
            $this->where[] = ['title','like', '%'.Request::input("title").'%'];
        }
		if (Request::input("id")) {
            $this->where[] = ['parent_id','=',Request::input("id")];
        }
		if (Request::input("category_id")) {
            $this->where[] = ['category_id','=',Request::input("category_id")];
        }
    }

	/**
     * 获取组结构列表
     * @return void
     */
    #[NoReturn] function treeAction(): void
    {
        $info = UserModel::query()
            ->with(["role"])
            ->where("id",$this->member_id)
            ->selectRaw("id,username,nickname,avatar,mobile,email,last_login_ip,last_login_time,role_id")
            ->first();
        if ($info) {
            $org = OrganizationModel::query()
                ->selectRaw("id,title,parent_id,category_id,sort,created_at")
                ->orderBy("sort",'desc')
                ->get()
                ->toArray();
            $orgList = $this->getTree($org,'parent_id');
            $this->apiSuccess($orgList,'获取成功',20000);
        }else {
            $this->apiError("账号异常");
        }
    }

    /**
     * 获取组织结构树
     * @return void
     */
    #[NoReturn] function orgTreeAction(): void
    {
        $org = OrganizationModel::query()
            ->selectRaw("id,title,parent_id,category_id,sort,created_at")
            ->orderBy("sort",'desc')
            ->get()
            ->toArray();
        $orgList = $this->getTree($org,'parent_id');
        $this->apiSuccess($orgList,'获取成功',20000);
    }
}
